#!/bin/bash

# This script is used to flash the SD card with the whole canmv-k230 system image.
# The image is built using the K230 SDK.
# It will overwrite the whole SD card, so be careful with the device name.
# The script will ask for confirmation before proceeding with the flashing process.
# It is recommended to run this script with sudo privileges.
# Usage: ./flashsd_canmv.sh

source ./envsetup

PATH_K230_LINUX_SDK=/home/u/ws/canaan/k230_linux_sdk
PATH_IF=${PATH_K230_LINUX_SDK}/output/${SOC_TYPE}_${BOARD_TYPE}_defconfig/images/sysimage-sdcard.img

if [[ -z "${DEV}" ]]; then
	DEV=/dev/sdb
fi

echo "==================="
print_env
echo "-------------------"
echo "DEV=$DEV"
echo "PATH_IF=$PATH_IF"
echo "==================="

read -p "Would you continue? [N/y]:" choice
case $choice in
Y | y)
	echo "======> Continue ......"
	;;
*)
	echo "======> Cancelled ...... Quitting now."
	exit
	;;
esac

if [ ! -b "${DEV}" ]; then
	echo "${DEV} does not exist!"
	exit 1
fi
# Sometimes the device may not be enumerated properly even if /dev/sdb exists,
# so continue to check to make sure the device is enumerated properly and at
# least one partition recognized.
if [ ! -b "${DEV}1" ]; then
	echo "${DEV}1 does not exist!"
	exit 1
fi

if [ ! -f "${PATH_IF}" ]; then
	echo "${PATH_IF} does not exist!"
	exit 1
fi

# Check dependencies ...
if ! command -v pv > /dev/null 2>&1 ; then
	echo "ERROR: pv is missing. Run 'apt install pv' to install it." 
	exit 1
fi

SIZE_IMAGE=`ls -lh ${PATH_IF} | awk '{print $5}'`

dd if=${PATH_IF} | pv -s ${SIZE_IMAGE} | sudo dd of=${DEV} bs=1M oflag=sync

